package com.nchu.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.nchu.domain.dto.PageDTO;
import com.nchu.domain.enums.UserStatus;
import com.nchu.domain.po.Address;
import com.nchu.domain.po.Result;
import com.nchu.domain.qo.UserQuery;
import com.nchu.domain.vo.AddressVO;
import com.nchu.domain.vo.UserVO;
import com.nchu.mapper.UserMapper;
import com.nchu.domain.po.User;
import com.nchu.service.UserService;
import org.springframework.stereotype.Service;

import javax.lang.model.element.VariableElement;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Override
    public void deductBalance(Long id, Integer money) {
        //1.查询用户
        User user = getById(id);
        //2.判断用户状态
        if (user == null || user.getStatus() == UserStatus.FREEZE){
            throw new RuntimeException("用户状态异常");
        }
        //3.判断用户余额
        if (user.getBalance() < money){
            throw new RuntimeException("用户余额不足");
        }
        //4.扣减
        //baseMapper.deductMoneyById(id,money);

        int inBalance = user.getBalance() - money;
        lambdaUpdate()
                .set(User::getBalance,inBalance)
                .set(inBalance == 0,User::getStatus,2)
                .eq(User::getId,id)
                .eq(User::getBalance,user.getBalance())
                .update();


    }

    @Override
    public UserVO queryUserAndAddressById(Long userId) {
        //1.查询用户
        User user = getById(userId);
        if (user == null || user.getStatus() == UserStatus.FREEZE){
            throw new RuntimeException("用户状态异常");
        }

        //2.查询收获地址
        List<Address> addressList = Db.lambdaQuery(Address.class).eq(Address::getUserId, userId).list();

        //3.处理vo
        //3.1 将user复制给userVo
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        //3.2 将addressList复制给addressVO
        if (CollUtil.isNotEmpty(addressList)){
            userVO.setAddress(BeanUtil.copyToList(addressList, AddressVO.class));
        }

        return userVO;
    }

    @Override
    public Result queryUserByIdList(List<Long> ids) {
        //1.查询用户
        List<User> users = listByIds(ids);

        //判断是否为空
        if (CollUtil.isEmpty(users)){
            //为空
            List<Object> emptyList = Collections.emptyList();
            return Result.success(emptyList);
        }
        //不为空
        //2.查询地址
        //2.1获取用户id集合
        List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());

        //2.2根据id查询地址
        List<Address> address = Db.lambdaQuery(Address.class).in(Address::getUserId, userIds).list();

        //2.3转换
        List<AddressVO> addressVOList = BeanUtil.copyToList(address, AddressVO.class);
        //2.4 用户地址集合分组处理 相同用户放到一个集合中
        Map<Long, List<AddressVO>> addressMap = new HashMap<>(0);
        if (CollUtil.isNotEmpty(addressVOList)){
            addressMap = addressVOList.stream().collect(Collectors.groupingBy(AddressVO::getUserId));
        }

        //3.转换
        List<UserVO> list = new ArrayList<>(users.size());
        //遍历 users 集合
        for (User user : users) {
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            list.add(userVO);
            userVO.setAddress(addressMap.get(user.getId()));
        }

        return Result.success(list);
    }

    @Override
    public PageDTO<UserVO> queryUserPage(UserQuery query) {
        String name = query.getName();
        Integer status = query.getStatus();

        Page<User> page = query.toMpPageDefaultUpdate();

        //2.分页查询
        Page<User> p = lambdaQuery().
                like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .page(page);

        //3.封装VO
        //return PageDTO.of(p,user -> BeanUtil.copyProperties(user,UserVO.class));

        return PageDTO.of(p,user -> {
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            //张三丰  张**
            String username = userVO.getUsername();
            userVO.setUsername(username.substring(0,username.length()-2)+"**");
            return userVO;
        });

    }
}
